/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.uc.service.impl;

import com.xy.biz.uc.domain.bo.RoleBO;
import com.xy.biz.uc.domain.enums.RoleTypeEnum;
import com.xy.biz.uc.domain.query.RoleIdQuery;
import com.xy.biz.uc.domain.query.RoleQuery;
import com.xy.biz.uc.manager.RoleManager;
import com.xy.biz.uc.service.RoleService;
import com.xy.lang.domain.Result;
import com.xy.tool.concurrent.locks.DisLock;
import com.xy.tool.concurrent.locks.DisLockFactory;
import com.xy.tool.context.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 
 * 
 * @author zsp
 * @date 2020-8-19
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleManager roleManager;
	@Autowired
	private DisLockFactory disLockFactory;
	
	@Override
	public Result<?> saveRole(RoleBO roleBO) {
		String roleCode = roleBO.getRoleCode();
		String lockKey = "role-" + roleCode;
		DisLock disLock = disLockFactory.create();
		if(disLock.lock(lockKey, 5000L)) {
			try {
				if(roleManager.isRoleCodeExists(roleCode)) {
					return Result.ofConflict("角色编号已存在",  roleCode);
				}
				roleBO.setType(RoleTypeEnum.CUSTOM.getCode());
				roleBO.setTenantId(UserContextHolder.getTenantId());
				LocalDateTime now = LocalDateTime.now();
				roleBO.setCreateTime(now);
				roleBO.setUpdateTime(now);
				int affectedRows = roleManager.saveRole(roleBO);
				if (affectedRows > 0) {
					return Result.success();
				}
			} finally {
				disLock.unlock(lockKey);
			}
		}
		return Result.ofErrorRowsAffected();
	}
	
	@Override
	public Result<?> updateRole(RoleBO roleBO) {
		roleBO.setUpdateTime(LocalDateTime.now());
		int affectedRows = roleManager.updateRole(roleBO);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}
	
	@Override
	public Result<?> deleteRole(Long roleId) {
		int affectedRows = roleManager.deleteRole(roleId);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}
	
	@Override
	public RoleBO getRole(RoleIdQuery roleIdQuery) {
		return roleManager.getRole(roleIdQuery);
	}
	
	@Override
	public List<RoleBO> listRoleById(RoleIdQuery roleIdQuery) {
		return roleManager.listRoleById(roleIdQuery);
	}
	
	@Override
	public List<RoleBO> listRole(RoleQuery query) {
		return roleManager.listRole(query);
	}
	
	@Override
	public int countRole(RoleQuery query) {
		return roleManager.countRole(query);
	}

	@Override
	public List<Long> listResourceIdByRoleId(Long roleId) {
		return roleManager.listResourceIdByRoleId(roleId);
	}

}
